import { query } from '../config/database.js'

export class User {
  /**
   * 根据用户名查找用户
   * @param {string} username
   * @returns {Promise<Object|null>}
   */
  static async findByUsername(username) {
    const sql = 'SELECT * FROM users WHERE username = ?'
    const rows = await query(sql, [username])
    return rows[0] || null
  }

  /**
   * 根据ID查找用户
   * @param {number} id
   * @returns {Promise<Object|null>}
   */
  static async findById(id) {
    const sql = 'SELECT id, username, name, role, created_at, updated_at FROM users WHERE id = ?'
    const rows = await query(sql, [id])
    return rows[0] || null
  }

  /**
   * 创建新用户
   * @param {Object} userData
   * @returns {Promise<Object>}
   */
  static async create({ username, name, passwordHash, role }) {
    const sql = 'INSERT INTO users (username, name, password_hash, role) VALUES (?, ?, ?, ?)'
    const result = await query(sql, [username, name, passwordHash, role])
    return this.findById(result.insertId)
  }

  /**
   * 获取所有用户
   * @returns {Promise<Array>}
   */
  static async findAll() {
    const sql = 'SELECT id, username, name, role, created_at, updated_at FROM users ORDER BY id'
    return await query(sql, [])
  }
}
